﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Projektarbete.Popup;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Projektarbete
{
    /// <summary>
    /// The inventory that comes up when you hit the inventory button
    /// </summary>
    class InventoryPopup : PopupBase
    {
        private enum Direction { Up, Down }; //För att det är enklare

        private Texture2D background;
        private Texture2D iconWeight;
        private Texture2D iconSize;
        private Texture2D iconValue;
        private SpriteFont spriteFont;
        private SpriteFont spriteFontSmall;

        private Vector2 position; //Position av fönstret (vart bakrunden ritas ut)
        private Point mousePoint; //Musposition

        private Item[] inventoryContents; //Vad som finns i spelaren inventory
        private Item selectedItem; //Vad spelaren har klicat på
        private int itemScroll; //Vart det börjas rita ut från inventoryContents
        private int maxItemScroll; //Hur långt man kan scrolla utan att gå utanför inventoryContents

        private string itemDescription; //Beskrivningen av vad man klickar på
        private string itemName;
        private string itemWeight;
        private string itemSize;
        private string itemValue;
        private string playerWeight; //Hur mycket som är i spelarens inventory
        private string playerSize;

        private Rectangle scissorRectangle; //Om något har en lång beskrivning, klipp ut allt som är utanför
        private Rectangle itemRectangle; //Kolla om musen är innanför den här, kolla sedan om spelaren klickar på något item. Så man inte behöver loopa igenom 22 föremål

        //Temporära variabler så att man inte skapar nya varje frame
        private Vector2 tempVector2;
        private Rectangle tempRectangle;
        private Point tempPoint;
        private int tempInt;

        //Vart saker ska ritas ut
        private Vector2 weightDrawPosition;
        private Vector2 sizeDrawPosition;

        private Vector2 itemDescriptionDrawPosition;
        private Vector2 itemDescriptionDrawPositionDefault;
        private Vector2 itemNameDrawPosition;
        private Vector2 itemWeightDrawPosition;
        private Vector2 itemSizeDrawPosition;
        private Vector2 itemValueDrawPosition;
        private Vector2 itemDescriptionInfoPosition;

        public InventoryPopup()
        {
            background = Global.LoadTexture2D("HUD/inventoryHUD");
            spriteFont = Global.LoadSpriteFont("Fonts/inventoryFont");
            spriteFontSmall = Global.LoadSpriteFont("Fonts/inventoryFontSmall");

            iconWeight = Global.LoadTexture2D("HUD/Inventory/iconWeight");
            iconSize = Global.LoadTexture2D("HUD/Inventory/iconSize");
            iconValue = Global.LoadTexture2D("HUD/Inventory/iconValue");

            itemRectangle = new Rectangle(55, 69, 345, 480); //CHANGE IF ITEM BOX IS CHANGED
            scissorRectangle = new Rectangle(418, 363, 324, 175); //CHANGE IF DESCRIPTION BOX IS CHANGED!

            position = new Vector2(40, 40);
            weightDrawPosition = new Vector2(126, 47);
            sizeDrawPosition = new Vector2(310, 47);

            itemDescriptionDrawPosition = new Vector2(420, 363);
            itemDescriptionDrawPositionDefault = itemDescriptionDrawPosition;
            itemNameDrawPosition = new Vector2(420, 343);
            itemWeightDrawPosition = new Vector2(420, 400);
            itemSizeDrawPosition = new Vector2(480, 400);
            itemDescriptionInfoPosition = new Vector2(585, 535);
            itemValueDrawPosition = Vector2.Zero;

            itemScroll = 0;
            maxItemScroll = 0;

            tempInt = 0;
            tempVector2 = Vector2.Zero;
            tempRectangle = Rectangle.Empty;
            tempPoint = Point.Zero;

            itemDescription = string.Empty;
            itemName = string.Empty;
            itemWeight = string.Empty;
            itemSize = string.Empty;
            itemValue = string.Empty;

            selectedItem = new ItemPresets.EmptySlot();

            inventoryContents = new Item[0];
        }

        public override void Update()
        {
            mousePoint = Input.GetMousePosition();

            if (itemRectangle.Contains(mousePoint))
            {
                tempInt = ToInventoryTile(mousePoint.Y);

                if (tempInt < inventoryContents.Length)
                {
                    selectedItem = inventoryContents[tempInt + itemScroll];
                    itemName = selectedItem.getName;
                    itemDescription = Global.TrimString(spriteFont, 324, selectedItem.getDescription);
                    itemWeight = selectedItem.getWeight.ToString();
                    itemSize = selectedItem.getSize.ToString();
                    itemValue = selectedItem.getValue.ToString();

                    itemDescriptionDrawPosition = itemDescriptionDrawPositionDefault;
                }
            }

            #region scrolling
            //TODO: CHANGE KEYCONFIG UP/DOWN/LEFT/RIGHT
            if (Input.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Up))
                if (Input.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftShift))
                    ScrollText(Direction.Up);
                else
                    Scroll(Direction.Up);
            else if (Input.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Down))
                if (Input.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftShift))
                    ScrollText(Direction.Down);
                else
                    Scroll(Direction.Down);

            if (Input.GetLastMouseWheelValueNormalized() != Input.GetMouseWheelValueNormalized())
            {
                if (Input.GetMouseWheelValueNormalized() > Input.GetLastMouseWheelValueNormalized())
                    if (Input.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftShift))
                        ScrollText(Direction.Up);
                    else
                        Scroll(Direction.Up);
                else
                    if (Input.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftShift))
                        ScrollText(Direction.Down);
                    else
                        Scroll(Direction.Down);
            }
            #endregion

            #region clicking
            if (Input.IsNewMouseOnePress())
            {
                switch (selectedItem.getType)
                {
                    case ItemTypes.HealthPotion:
                    case ItemTypes.ManaPotion:
                        Player.DrinkItem(selectedItem);
                        UpdateInventoryContents();
                        break;
                    case ItemTypes.Arm:
                    case ItemTypes.Chest:
                    case ItemTypes.Hand:
                    case ItemTypes.Head:
                    case ItemTypes.Leg:
                    case ItemTypes.Shoe:
                        Player.EquipItem(selectedItem);
                        UpdateInventoryContents();
                        break;
                }
            }

            #region rightclick
            if (Input.IsNewMouseTwoPress())
            {
                mousePoint = Input.GetMousePosition();

                tempInt = ToInventoryTile(mousePoint.Y);

                if (itemRectangle.Contains(mousePoint))
                {
                    if (tempInt + itemScroll < inventoryContents.Length)
                        if(PopupManager.DropItem(inventoryContents[tempInt + itemScroll]))
                            ClearSelectedItem();
                }
            }
            #endregion
            #endregion
        }

        /// <summary>
        /// Converts where the user clicks to which item should be accessed in inventoryContents[x]
        /// </summary>
        /// <param name="y">Mouse y-position</param>
        /// <returns></returns>
        private int ToInventoryTile(int y)
        {
            return (int)Math.Floor((y - 70) / 30f); //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!
        }

        /// <summary>
        /// Updates the inventorycontents to display
        /// </summary>
        public void UpdateInventoryContents()
        {
            inventoryContents = Player.inventory.GetContentsAsArray;

            //TODO: FIX ITEMSCROLL
            //itemScroll = 0;
            //maxItemScroll = itemScroll + 16; //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!

            maxItemScroll = itemScroll + 16; //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!

            if (maxItemScroll >= inventoryContents.Length)
                maxItemScroll = inventoryContents.Length;

            itemScroll = maxItemScroll - 16; //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!

            if (itemScroll < 0)
                itemScroll = 0;

            playerWeight = Player.inventory.getCurrentWeight.ToString() + "/" + Player.inventory.getMaxWeight.ToString();
            playerSize = Player.inventory.getCurrentSize.ToString() + "/" + Player.inventory.getMaxSize.ToString();

            itemRectangle.Height = inventoryContents.Length * 30;

            if (itemRectangle.Height > 480)
                itemRectangle.Height = 480;
        }

        /// <summary>
        /// Scrolls the items
        /// </summary>
        /// <param name="direction"></param>
        private void Scroll(Direction direction)
        {
            if (direction == Direction.Up)
            {
                itemScroll--;

                UpdateItemScroll();
            }
            else if (direction == Direction.Down)
            {
                itemScroll++;

                UpdateItemScroll();
            }
        }

        private void ScrollText(Direction direction)
        {
            if (direction == Direction.Up)
            {
                if (itemDescriptionDrawPosition.Y < 363)
                    itemDescriptionDrawPosition.Y += 5;
            }
            else
            {
                if (itemDescriptionDrawPosition.Y > 363 - (int)spriteFont.MeasureString(itemDescription).Y + 175)
                    itemDescriptionDrawPosition.Y -= 5;
            }
        }

        /// <summary>
        /// Clears the selected item
        /// </summary>
        public void ClearSelectedItem()
        {
            selectedItem = new ItemPresets.EmptySlot();

            itemDescription = string.Empty;
            itemName = string.Empty;
            itemWeight = string.Empty;
            itemSize = string.Empty;
            itemValue = string.Empty;

            itemDescriptionDrawPosition = itemDescriptionDrawPositionDefault;
        }

        /// <summary>
        /// Clamps ItemScroll, updates MaxItemScroll and clamps it
        /// </summary>
        private void UpdateItemScroll()
        {
            if (itemScroll < 0)
                itemScroll = 0;

            //Se till så att itemScroll
            if (itemScroll >= inventoryContents.Length - 16) //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!
                itemScroll = inventoryContents.Length - 16; //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!

            maxItemScroll = itemScroll + 16; //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!

            if (maxItemScroll >= inventoryContents.Length)
                maxItemScroll = inventoryContents.Length;

            if (itemScroll < 0)
                itemScroll = 0;
        }

        /// <summary>
        /// Draws the entire popup
        /// </summary>
        /// <param name="spriteBatch">spritebatch</param>
        /// <param name="graphicsDevice">graphicsDevice</param>
        public override void Draw(SpriteBatch spriteBatch, GraphicsDevice graphicsDevice)
        {
            spriteBatch.Draw(background, position, Color.White);

            for (int x = itemScroll; x < maxItemScroll; x++)
            {
                //Bild
                tempVector2.X = 59;
                tempVector2.Y = 70 + (x - itemScroll) * 30;
                //TODO: COLORS?
                spriteBatch.Draw(inventoryContents[x].getTexture, tempVector2, Color.White); //Items bild

                //Text
                tempVector2.X = 80;
                tempVector2.Y = 65 + (x - itemScroll) * 30;

                spriteBatch.DrawString(spriteFont, inventoryContents[x].getName, tempVector2, Color.White); //Items namn

                //Bilder
                tempVector2.Y = 85 + (x - itemScroll) * 30;

                spriteBatch.Draw(iconValue, tempVector2, Color.White); //Rita ut ikonen för värde

                tempVector2.X = 150;

                spriteBatch.Draw(iconWeight, tempVector2, Color.White); //Rita ut ikonen för vikt

                tempVector2.X = 200;

                spriteBatch.Draw(iconSize, tempVector2, Color.White); //Rita ut ikonen för storlek

                tempVector2.X = 110;


                //Text
                tempVector2.Y = 81 + (x - itemScroll) * 30;

                tempVector2.X = 90;

                spriteBatch.DrawString(spriteFontSmall, inventoryContents[x].getValue.ToString(), tempVector2, Color.White); //Guld

                tempVector2.X = 160;

                spriteBatch.DrawString(spriteFontSmall, inventoryContents[x].getWeight.ToString(), tempVector2, Color.White); //Vikt

                tempVector2.X = 210;

                spriteBatch.DrawString(spriteFontSmall, inventoryContents[x].getSize.ToString(), tempVector2, Color.White); //Storlek
            }

            spriteBatch.DrawString(spriteFont, playerWeight, weightDrawPosition, Color.White); //Spelarens inventorys vikt + maxvikt
            spriteBatch.DrawString(spriteFont, playerSize, sizeDrawPosition, Color.White); //Spelarens inventorys storlek + maxstorlek

            spriteBatch.DrawString(spriteFont, itemName, itemNameDrawPosition, Color.White);

            if (itemName != string.Empty) //Om spelaren har klickat på ett item
            {
                //Bilder
                tempVector2.X = 576;
                tempVector2.Y = 539;

                spriteBatch.Draw(iconValue, tempVector2, Color.White); //Rita ut ikonen för värde

                tempVector2.X = 646;

                spriteBatch.Draw(iconWeight, tempVector2, Color.White); //Rita ut ikonen för vikt

                tempVector2.X = 696;

                spriteBatch.Draw(iconSize, tempVector2, Color.White); //Rita ut ikonen för storlek

                //Text
                tempVector2.X = 585;
                tempVector2.Y = 535;

                spriteBatch.DrawString(spriteFontSmall, itemValue, tempVector2, Color.White); //Guld

                tempVector2.X = 655;

                spriteBatch.DrawString(spriteFontSmall, itemWeight, tempVector2, Color.White); //Vikt

                tempVector2.X = 705;

                spriteBatch.DrawString(spriteFontSmall, itemSize, tempVector2, Color.White); //Storlek

                spriteBatch.End();

                graphicsDevice.RasterizerState = new RasterizerState() { ScissorTestEnable = true };
                graphicsDevice.ScissorRectangle = scissorRectangle;

                spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, graphicsDevice.RasterizerState);

                spriteBatch.DrawString(spriteFont, itemDescription, itemDescriptionDrawPosition, Color.White);

                spriteBatch.End();

                //TODO: REMOVE ??
                spriteBatch.Begin();
            }
        }
    }
}